import React, { useState } from 'react'
import {
  Box,
  Grid,
  Typography,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  Paper,
  TextField,
  RadioGroup,
  FormControlLabel,
  Radio,
  Button,
  Slider
} from '@mui/material'
import { PieChart, Pie, Cell, Tooltip } from 'recharts'

// 样式色彩
const COLORS = ['#4AA9FF', '#3DE0FF', '#5FE3B9', '#FFBD68', '#FF7A7A']
const BACKGROUND_COLOR = '#0F1E36'
const CARD_COLOR = '#1D2B45'
const GRID_COLOR = 'repeating-linear-gradient(0deg, #263952 0px, #263952 1px, transparent 1px, transparent 40px), repeating-linear-gradient(90deg, #263952 0px, #263952 1px, transparent 1px, transparent 40px)'

type Indicator = {
  name: string
  type: '定量' | '定性'
  weight: number
  desc?: string
  formula?: string
}

const defaultIndicators: Indicator[] = [
  { name: '数据治理能力', type: '定性', weight: 20 },
  { name: '数据分析能力', type: '定量', weight: 30 },
  { name: '业务流程数字化率', type: '定量', weight: 25 },
  { name: '数字化人才占比', type: '定量', weight: 15 },
  { name: '数字化创新能力', type: '定性', weight: 10 },
]

export default function App() {
  const [indicators, setIndicators] = useState<Indicator[]>(defaultIndicators)
  const [selected, setSelected] = useState<Indicator>(defaultIndicators[1]) // 默认选中第2个
  const totalWeight = indicators.reduce((sum, i) => sum + i.weight, 0)

  const handleFieldChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value } = e.target
    setSelected(prev => ({ ...prev, [name]: value }))
  }

  const handleSliderChange = (index: number, newValue: number) => {
    const updated = indicators.map((ind, i) => i === index ? { ...ind, weight: newValue } : ind)
    setIndicators(updated)
    if (selected.name === indicators[index].name) {
      setSelected({ ...selected, weight: newValue })
    }
  }

  const handleSave = () => {
    const updated = indicators.map(ind => ind.name === selected.name ? selected : ind)
    setIndicators(updated)
  }

  return (
    <Box sx={{
      minHeight: '100vh',
      backgroundColor: BACKGROUND_COLOR,
      backgroundImage: GRID_COLOR,
      color: '#fff',
      p: 3,
    }}>
      <Grid container spacing={2}>
        {/* 左侧 - 表格 */}
        <Grid item xs={12} md={4}>
          <Paper sx={{ backgroundColor: CARD_COLOR, borderRadius: 2, p: 2 }}>
            <Typography variant="h6" gutterBottom>📋 指标列表</Typography>
            <TableContainer>
              <Table size="small" sx={{ color: '#fff' }}>
                <TableHead>
                  <TableRow>
                    <TableCell sx={{ color: '#aaa' }}>指标名称</TableCell>
                    <TableCell sx={{ color: '#aaa' }}>类型</TableCell>
                    <TableCell sx={{ color: '#aaa' }}>权重</TableCell>
                  </TableRow>
                </TableHead>
                <TableBody>
                  {indicators.map((row) => (
                    <TableRow
                      key={row.name}
                      hover
                      onClick={() => setSelected(row)}
                      sx={{ cursor: 'pointer', '&:hover': { backgroundColor: '#2A3C5B' } }}
                    >
                      <TableCell sx={{ color: '#fff' }}>{row.name}</TableCell>
                      <TableCell sx={{ color: '#fff' }}>{row.type}</TableCell>
                      <TableCell sx={{ color: '#fff' }}>{row.weight}%</TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </TableContainer>
            <Box mt={1} fontSize={12} color="#888">🛈 支持定量与定性指标类型配置</Box>
          </Paper>
        </Grid>

        {/* 中间 - 编辑表单 */}
        <Grid item xs={12} md={4}>
          <Paper sx={{ backgroundColor: CARD_COLOR, borderRadius: 2, p: 2 }}>
            <Typography variant="h6" gutterBottom>🛠️ 指标编辑区</Typography>
            <TextField
              label="指标名称"
              name="name"
              fullWidth
              value={selected.name}
              onChange={handleFieldChange}
              sx={{ my: 1 }}
              InputProps={{ sx: { color: 'white' } }}
              InputLabelProps={{ sx: { color: '#aaa' } }}
            />
            <TextField
              label="指标描述"
              name="desc"
              fullWidth
              multiline
              rows={3}
              value={selected.desc || ''}
              onChange={handleFieldChange}
              sx={{ my: 1 }}
              InputProps={{ sx: { color: 'white' } }}
              InputLabelProps={{ sx: { color: '#aaa' } }}
            />
            <RadioGroup row name="type" value={selected.type} onChange={handleFieldChange}>
              <FormControlLabel value="定量" control={<Radio sx={{ color: '#4AA9FF' }} />} label="定量" />
              <FormControlLabel value="定性" control={<Radio sx={{ color: '#4AA9FF' }} />} label="定性" />
            </RadioGroup>
            <TextField
              label="评分规则配置"
              name="formula"
              fullWidth
              value={selected.formula || ''}
              onChange={handleFieldChange}
              sx={{ my: 1 }}
              InputProps={{ sx: { color: 'white' } }}
              InputLabelProps={{ sx: { color: '#aaa' } }}
            />
            <Button variant="contained" onClick={handleSave} sx={{ mt: 1 }}>保存</Button>
            <Box mt={2} fontSize={12} color="#888">🛈 实时权重总和校验</Box>
          </Paper>
        </Grid>

        {/* 右侧 - 权重滑动 + 饼图 */}
        <Grid item xs={12} md={4}>
          <Paper sx={{ backgroundColor: CARD_COLOR, borderRadius: 2, p: 2 }}>
            <Typography variant="h6" gutterBottom>⚖️ 权重分配可视化</Typography>
            {indicators.map((item, idx) => (
              <Box key={item.name} sx={{ mb: 2 }}>
                <Typography fontSize={14}>{item.name}: {item.weight}%</Typography>
                <Slider
                  value={item.weight}
                  min={0}
                  max={100}
                  step={1}
                  valueLabelDisplay="auto"
                  sx={{ color: '#4AA9FF' }}
                  onChange={(e, val) => handleSliderChange(idx, val as number)}
                />
              </Box>
            ))}
            <Typography fontSize={14} color={totalWeight === 100 ? '#4CAF50' : '#FF5252'}>
              权重总和: {totalWeight}%
            </Typography>

            <PieChart width={260} height={200}>
              <Pie
                data={indicators}
                dataKey="weight"
                nameKey="name"
                outerRadius={70}
                label
              >
                {indicators.map((entry, index) => (
                  <Cell key={index} fill={COLORS[index % COLORS.length]} />
                ))}
              </Pie>
              <Tooltip />
            </PieChart>
            <Box fontSize={12} color="#888">🛈 支持上级指标自动分配给下级指标</Box>
          </Paper>
        </Grid>
      </Grid>
    </Box>
  )
}
